package com.xiaohei.process.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.xiaohei.model.process.ProcessTemplate;
import com.xiaohei.model.process.ProcessType;
import com.xiaohei.process.mapper.ProcessTemplateMapper;
import com.xiaohei.process.mapper.ProcessTypeMapper;
import com.xiaohei.process.service.ProcessService;
import com.xiaohei.process.service.ProcessTemplateService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xiaohei.process.service.ProcessTypeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 审批模板 服务实现类
 * </p>
 *
 * @author xiaohei
 * @since 2024-05-05
 */
@Service
public class ProcessTemplateServiceImpl extends ServiceImpl<ProcessTemplateMapper, ProcessTemplate> implements ProcessTemplateService {

    @Autowired
    private ProcessTemplateService processTemplateService;
    @Autowired
    private ProcessTypeService processTypeService;
    @Autowired
    private ProcessService processService;

    @Override
    public Page<ProcessTemplate> selectPageProcessTemplate(Page<ProcessTemplate> pageParam) {
        //1. 调用mapper的方法实现分页查询
        Page<ProcessTemplate> pageObject = baseMapper.selectPage(pageParam,null);
        //2. 第一步分页查询返回分页数据  从分页数据获取列表list集合
        List<ProcessTemplate> processTemplateList = pageObject.getRecords();
        //3. 遍历list集合，得到每个对象的审批类型id
        for(ProcessTemplate process : processTemplateList){
            Long processTypeId = process.getProcessTypeId();
            //4.根据审批类型id  查询获取对应名称
            LambdaQueryWrapper<ProcessType> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(ProcessType::getId, processTypeId);
            ProcessType processType = processTypeService.getOne(wrapper);
            if(processType == null){
                continue;
            }
            //5. 完成封装
            process.setProcessTypeName(processType.getName());
        }
        return pageObject;
    }

    //部署流程定义(发布)
    @Override
    public void publish(Long id) {
        //修改模版状态
        ProcessTemplate processTemplate = processTemplateService.getById(id);
        processTemplate.setStatus(1);
        processTemplateService.updateById(processTemplate);

        if(!StringUtils.isEmpty(processTemplate.getProcessDefinitionPath())){
            processService.deployByZip(processTemplate.getProcessDefinitionPath());
        }

    }
}
